package me.zhengjie.modules.security.rest;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.aop.log.Log;
import me.zhengjie.config.WxMiniConfig;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.business.domain.WxUser;
import me.zhengjie.modules.business.service.WxUserService;
import me.zhengjie.modules.business.service.dto.WxUserDto;
import me.zhengjie.modules.business.util.WeChatGetUserInfoUtil;
import me.zhengjie.modules.security.security.vo.WxAuthUser;
import me.zhengjie.utils.RedisUtils;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author churuitao
 * date 2020-2-6
 * 授权、根据token获取用户详细信息
 */
@RestController
@RequestMapping("/wxAuth")
@Api(tags = "业务：微信小程序授权接口")
public class WxAuthController {

//    @Value("${loginCode.expiration}")
//    private Long expiration;
//    @Value("${rsa.private_key}")
//    private String privateKey;
//    @Value("${single.login:false}")
//    private Boolean singleLogin;
    private final RedisUtils redisUtils;
    private final WxUserService wxUserService;

    public WxAuthController(WxUserService wxUserService, RedisUtils redisUtils) {
        this.wxUserService = wxUserService;
        this.redisUtils = redisUtils;

    }

    @Log("微信用户登录")
    @ApiOperation("微信登录授权")
    @AnonymousAccess
    @PostMapping(value = "/login")
    public ResponseEntity<Object> login(@Validated @RequestBody WxAuthUser wxAuthUser, HttpServletRequest request) {
        System.out.println("-----/login-----");
        System.out.println(wxAuthUser);
        ValidationUtil.isNull(wxAuthUser.getCode(),"WxUser","code",wxAuthUser.getCode());
        String result = HttpUtil.get(WxMiniConfig.code2SessionUrl.replace("APPID",WxMiniConfig.APPID).replace("SECRET",WxMiniConfig.APPSECRET)
                .replace("JSCODE",wxAuthUser.getCode()), CharsetUtil.CHARSET_UTF_8);
        System.out.println("------result------");
        System.out.println(result);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        WxUserDto wxUserDto = null;
        if(jsonObject.getStr("openid")!=null){
            String  sessionKey = jsonObject.getStr("session_key");
            String openid = jsonObject.getStr("openid");
            JSONObject userInfoJSON= WeChatGetUserInfoUtil.getUserInfo(wxAuthUser.getEncryptedData(),sessionKey,wxAuthUser.getIv());
            System.out.println("----------userInfoJSON------------");
            System.out.println(userInfoJSON);
            if(userInfoJSON!=null){

                //这步应该set进实体类
                wxUserDto = wxUserService.findWxUserByMiniOpenid(userInfoJSON.getStr("openId"));
                if(wxUserDto.getId()==null){
                    WxUser wxUser = new WxUser();
                    wxUser.setEnabled(true);
                    wxUser.setMiniOpenId(userInfoJSON.getStr("openId"));
                    wxUser.setOrientation(wxAuthUser.getOrientation());
//                    userInfoJSON.getStr("nickName")
                    wxUser.setNickName("爱心支教");
                    wxUser.setSex(userInfoJSON.getInt("gender")!=0?(userInfoJSON.getInt("gender")==1?"男":"女"):"未知");
                    wxUser.setAvatar(userInfoJSON.getStr("avatarUrl"));
                    if (userInfoJSON.getStr("unionId")!=null) {
                        wxUser.setUnionId(userInfoJSON.getStr("unionId"));
                    }
                    wxUserDto = wxUserService.create(wxUser);
                }
//                String uuid=UUID.randomUUID().toString();
//                dataMap.put("WXTOKEN", uuid);
//                redisTemplate.opsForValue().set(uuid,userInfo);
//                redisTemplate.expire(uuid,appTimeOut,TimeUnit.SECONDS);
               return new ResponseEntity<>(wxUserDto,HttpStatus.OK);
            }else throw new BadRequestException("解密失败");
        }else throw new BadRequestException("code错误，请稍后重试");
    }

    @ApiOperation("微信登录授权")
    @AnonymousAccess
    @PostMapping(value = "/test-login")
    public ResponseEntity<Object> testLogin(@Validated @RequestBody WxAuthUser wxAuthUser, HttpServletRequest request) {

        return ResponseEntity.ok(null);
    }
}
